﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TXLooker.Common;
using TXLooker.WorkItemExtention.Core;
using TXLooker.WorkItemExtention.Properties;

namespace TXLooker.WorkItemExtention.UI.QueryManager
{
    public partial class QueryGridControl : UserControl
    {
        // Methods
        private QueryGridControl()
        {
            this.m_bEndUpdate = false;
            this.m_From = "FROM WorkItems";
            this.m_OrderBy = "ORDER BY [System.Id]";
            this.m_comboAndOr = new ComboBox();
            this.m_comboField = new ComboBox();
            this.m_comboOperator = new ComboBox();
            this.m_comboValue = new ComboBox();
            this.m_comboTreeValue = new ComboBoxTree();
            this.m_SysBack = new SolidBrush(SystemColors.Highlight);
            this.m_store = null;
            this.m_operatorsDictionary = new Dictionary<string, string[]>();
            this.m_fieldDictionary = new Dictionary<string, FieldDefinition>();
            this.m_groupCollection = new List<Group>();
            this.m_distancePixel = 0;
            this.m_pointLastCell = new Point(-1, -1);
            this.m_allowePaint = false;
            this.m_columnsWidthResulGrid = new List<int>();
            this.components = null;
            this.InitializeComponent();
            this.m_tfsTreeCtrl.LoadF();
            this.m_tfsTreeCtrl.SelectionChanged += new EventHandler(this.OnTFSSelectesChange);
            this.m_queryGrid.Enabled = false;
            this.InitComboBoxes();
            this.DeleteNonFilledClauses = (EventHandler)Delegate.Combine(this.DeleteNonFilledClauses, new EventHandler(this.OnDeleteNonFilledClauses));
        }

        public QueryGridControl(IOlWorkItemProcessor olProccessor)
            : this()
        {
            this.m_olProccessor = olProccessor;
        }

        private void AddSimpleRow()
        {
            DataGridViewRow dataGridViewRow = new DataGridViewRow();
            this.m_queryGrid.Rows.Add(dataGridViewRow);
            this.m_allowePaint = true;
        }

        private void BuildAndOr(int i, int j)
        {
            if (this.m_queryGrid[j, i].Value != null)
            {
                this.m_queryString = this.m_queryString + (this.m_queryGrid[j, i].Value as string).ToUpper() + " ";
            }
        }

        private void BuildField(List<int> firstGroupIndexes, int i, int j)
        {
            if (this.m_queryGrid[j, i].Value != null)
            {
                int num = 0;
                foreach (int num2 in firstGroupIndexes)
                {
                    if (num2 == i)
                    {
                        this.m_queryString = this.m_queryString + '(' + " ";
                        num++;
                    }
                }
                for (uint k = 0; k < num; k++)
                {
                    firstGroupIndexes.Remove(i);
                }
                FieldDefinition definition = this.m_fieldDictionary[this.m_queryGrid[j, i].Value as string];
                this.m_queryString = this.m_queryString + string.Format("[{0}] ", definition.ReferenceName);
            }
        }

        private string BuildOperator(int i, int j)
        {
            string str = string.Empty;
            if ((this.m_queryGrid[j, i].Value != null) || (string.Empty != ((string)this.m_queryGrid[j, i].Value)))
            {
                switch (((string)this.m_queryGrid[j, i].Value))
                {
                    case "In":
                        str = "IN";
                        break;

                    case "Was Ever":
                        str = "EVER";
                        break;

                    case "Contains":
                        str = "CONTAINS";
                        break;

                    case "Does Not Contain":
                        str = "NOT CONTAINS";
                        break;

                    case "Under":
                        str = "UNDER";
                        break;

                    case "Not Under":
                        str = "NOT UNDER";
                        break;

                    default:
                        str = this.m_queryGrid[j, i].Value + "";
                        break;
                }
                this.m_queryString = this.m_queryString + str + " ";
            }
            return str;
        }

        private void BuildQuery()
        {
            this.GetSelectedColumns();
            this.DisableComboBoxes();
            this.m_queryString = string.Empty;
            this.m_queryString = string.Format("{0} {1} {2} ", this.m_Select, this.m_From, "WHERE");
            List<int> firstGroupIndexes = new List<int>();
            List<int> lastGroupIndexes = new List<int>();
            foreach (Group group in this.m_groupCollection)
            {
                firstGroupIndexes.Add(group.FirstRow);
                lastGroupIndexes.Add(group.LastRow);
            }
            string strOperator = string.Empty;
            for (int i = 0; i < this.m_queryGrid.Rows.Count; i++)
            {
                for (int j = 0; j < (this.m_queryGrid.Columns.Count - 1); j++)
                {
                    if (this.m_queryGrid.Columns[1] == this.m_queryGrid.Columns[j])
                    {
                        this.BuildAndOr(i, j);
                    }
                    else if (this.m_queryGrid.Columns[2] == this.m_queryGrid.Columns[j])
                    {
                        this.BuildField(firstGroupIndexes, i, j);
                    }
                    else if (this.m_queryGrid.Columns[3] == this.m_queryGrid.Columns[j])
                    {
                        strOperator = this.BuildOperator(i, j);
                    }
                    else if (this.m_queryGrid.Columns[4] == this.m_queryGrid.Columns[j])
                    {
                        this.BuildValue(lastGroupIndexes, i, j, strOperator);
                    }
                }
            }
            this.m_queryString = this.m_queryString + this.m_OrderBy;
            Debug.WriteLine("Query:\t" + this.m_queryString);
        }

        private void BuildValue(List<int> lastGroupIndexes, int i, int j, string strOperator)
        {
            if (this.m_queryGrid[j, i].Value != null)
            {
                string str = (string)this.m_queryGrid[j, i].Value;
                if (str.Contains("@"))
                {
                    this.m_queryString = this.m_queryString + string.Format("{0} ", str);
                }
                else if ((strOperator == "In") || (strOperator == "IN"))
                {
                    this.m_queryString = this.m_queryString + string.Format("('{0}') ", str);
                }
                else
                {
                    this.m_queryString = this.m_queryString + string.Format("'{0}' ", this.m_queryGrid[j, i].Value);
                }
                int num = 0;
                foreach (int num2 in lastGroupIndexes)
                {
                    if (num2 == i)
                    {
                        object queryString = this.m_queryString;
                        this.m_queryString = string.Concat(new object[] { queryString, " ", ')', " " });
                        num++;
                    }
                }
                for (uint k = 0; k < num; k++)
                {
                    lastGroupIndexes.Remove(i);
                }
            }
        }

        private bool CheckToAllowGroup(bool bAllowGroup, int firstRowSelectedIndex, int lastRowSelectedIndex)
        {
            foreach (Group group in this.m_groupCollection)
            {
                if ((lastRowSelectedIndex < group.FirstRow) || (group.LastRow < firstRowSelectedIndex))
                {
                    bAllowGroup = true;
                }
                else
                {
                    bAllowGroup = false;
                    if ((group.FirstRow == firstRowSelectedIndex) && (group.LastRow < lastRowSelectedIndex))
                    {
                        bAllowGroup = true;
                        this.m_distancePixel += 3;
                        return bAllowGroup;
                    }
                    if ((group.LastRow == lastRowSelectedIndex) && (group.FirstRow > firstRowSelectedIndex))
                    {
                        bAllowGroup = true;
                        this.m_distancePixel += 3;
                        return bAllowGroup;
                    }
                    if ((group.LastRow < lastRowSelectedIndex) && (group.FirstRow > firstRowSelectedIndex))
                    {
                        bAllowGroup = true;
                        this.m_distancePixel += 3;
                    }
                    else
                    {
                        bAllowGroup = false;
                        return bAllowGroup;
                    }
                }
            }
            return bAllowGroup;
        }

        private void CheckToAllowUngroup(ref bool bAllowUngroup, ref bool bAllowGroup, int firstRowSelectedIndex, int lastRowSelectedIndex)
        {
            foreach (Group group in this.m_groupCollection)
            {
                if ((group.FirstRow == firstRowSelectedIndex) && (group.LastRow == lastRowSelectedIndex))
                {
                    bAllowUngroup = true;
                    bAllowGroup = false;
                }
            }
        }

        private void ComboBoxStart(ComboBox comboBox)
        {
            comboBox.Visible = false;
            this.m_comboAndOr.Width = 0;
            comboBox.Left = this.CellLeft;
            comboBox.Top = this.CellTop - (this.m_rowNewValue * this.m_queryGrid.Rows[0].Height);
            comboBox.Width = this.CellWidth;
            comboBox.BringToFront();
            comboBox.Text = this.m_queryGrid.CurrentCell.Value + "";
            comboBox.Visible = true;
            comboBox.Focus();
        }

        private void DeleteStoredQuery(WIStoredQuery wiQuery)
        {
            try
            {
                StoredQueryCollection querys = WorkItemExtentionGlobal.FindStoredQueries(wiQuery);
                if (querys != null)
                {
                    StoredQuery storedQuery = null;
                    foreach (StoredQuery query2 in querys)
                    {
                        if (query2.QueryGuid == wiQuery.QueryGuid)
                        {
                            storedQuery = query2;
                        }
                    }
                    if (storedQuery != null)
                    {
                        try
                        {
                            querys.Remove(storedQuery);
                            this.Update(wiQuery);
                        }
                        catch (UnauthorizedAccessException exception)
                        {
                            MessageBox.Show(exception.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        }
                        catch (Exception exception3)
                        {
                            LogManager.WriteMessageToCustomLog("Error in DeleteStoredQuery " + exception3.ToString());
                        }
                    }
                }
            }
            catch (Exception exception4)
            {
                LogManager.WriteMessageToCustomLog("Error in DeleteStoredQuery " + exception4.ToString());
            }
        }

        private void DisableComboBoxes()
        {
            this.m_comboAndOr.Visible = false;
            this.m_comboAndOr.Width = 0;
            this.m_comboField.Visible = false;
            this.m_comboField.Width = 0;
            this.m_comboOperator.Visible = false;
            this.m_comboOperator.Width = 0;
            this.m_comboValue.Visible = false;
            this.m_comboValue.Width = 0;
            this.m_comboTreeValue.Visible = false;
            this.m_comboTreeValue.Width = 0;
        }

        private void DrawLastRowWithoutSeparateLines(DataGridViewCellPaintingEventArgs e)
        {
            if ((e.RowIndex == (this.m_queryGrid.RowCount - 1)) && (e.ColumnIndex > 0))
            {
                e.Handled = true;
                e.Graphics.FillRectangle(new SolidBrush(SystemColors.HighlightText), e.CellBounds);
                e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X, e.CellBounds.Y, e.CellBounds.X + e.CellBounds.Width, e.CellBounds.Y);
                e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X, (e.CellBounds.Y + e.CellBounds.Height) - 1, e.CellBounds.X + e.CellBounds.Width, (e.CellBounds.Y + e.CellBounds.Height) - 1);
            }
        }

        private void DrawTextLastRow(DataGridViewCellPaintingEventArgs e)
        {
            if ((e.RowIndex == (this.m_queryGrid.RowCount - 1)) && (e.ColumnIndex == 1))
            {
                this.m_pointLastCell = new Point(e.CellBounds.X + 2, e.CellBounds.Y + 2);
            }
        }

        private void EnableCombobBoxes(bool bEnable)
        {
            this.m_comboAndOr.Visible = bEnable;
            this.m_comboField.Visible = bEnable;
            this.m_comboOperator.Visible = bEnable;
            this.m_comboValue.Visible = bEnable;
            this.m_comboTreeValue.Visible = bEnable;
        }

        private void EnableControls(bool bEnable)
        {
            this.m_queryGrid.Enabled = bEnable;
            this.m_deleteQueryToolStripMenuItem.Enabled = bEnable;
            this.m_toolStripTextBoxQueryName.Enabled = bEnable;
            this.m_saveToolStripMenuItem.Enabled = bEnable;
            this.m_executeToolStripMenuItem.Enabled = bEnable;
            this.m_saveToolStripMenuItem.Enabled = bEnable;
            this.m_fileSaveToolStripMenuItem.Enabled = bEnable;
            this.m_updateQueryToolStripMenuItem.Enabled = bEnable;
            this.m_allowePaint = bEnable;
            this.m_columnOptionsToolStripMenuItem.Enabled = bEnable;
            this.m_renameQueryToolStrip.Enabled = bEnable;
        }

        private void ExpandNodes(List<TreeNode> expandedNodes)
        {
            foreach (TreeNode node in expandedNodes)
            {
                foreach (TreeNode node2 in this.m_tfsTreeCtrl.TreeView.Nodes)
                {
                    if (node2.Text == node.Text)
                    {
                        node2.Expand();
                    }
                    foreach (TreeNode node3 in node2.Nodes)
                    {
                        if (node3.Text == node.Text)
                        {
                            node3.Expand();
                        }
                        foreach (TreeNode node4 in node3.Nodes)
                        {
                            if (node4.Text == node.Text)
                            {
                                node4.Expand();
                            }
                            foreach (TreeNode node5 in node4.Nodes)
                            {
                                if (node5.Text == node.Text)
                                {
                                    node5.Expand();
                                }
                            }
                        }
                    }
                }
            }
        }

        private void FillFieldComboBox(WorkItemStore store)
        {
            this.m_comboField.Items.Clear();
            this.m_fieldDictionary.Clear();
            FieldDefinitionCollection fieldDefinitions = store.FieldDefinitions;
            List<string> list = new List<string>();
            foreach (FieldDefinition definition in fieldDefinitions)
            {
                list.Add(definition.Name);
                this.m_fieldDictionary.Add(definition.Name, definition);
            }
            list.Sort(new Comparison<string>(this.SortByName));
            foreach (string str in list)
            {
                this.m_comboField.Items.Add(str);
            }
        }

        private List<TreeNode> GetExpandedNodes()
        {
            List<TreeNode> list = new List<TreeNode>();
            foreach (TreeNode node in this.m_tfsTreeCtrl.TreeView.Nodes)
            {
                if (node.Nodes.Count > 0)
                {
                    foreach (TreeNode node2 in node.Nodes)
                    {
                        if (node2.Nodes.Count > 0)
                        {
                            foreach (TreeNode node3 in node2.Nodes)
                            {
                                if (node3.Nodes.Count > 0)
                                {
                                    foreach (TreeNode node4 in node3.Nodes)
                                    {
                                        if (node4.IsExpanded)
                                        {
                                            list.Add(node4);
                                        }
                                    }
                                }
                                if (node3.IsExpanded)
                                {
                                    list.Add(node3);
                                }
                            }
                        }
                        if (node2.IsExpanded)
                        {
                            list.Add(node2);
                        }
                    }
                }
                if (node.IsExpanded)
                {
                    list.Add(node);
                }
            }
            return list;
        }

        private Project GetProject(WIObject item)
        {
            Project project = null;
            WIObject selectedObject = this.m_tfsTreeCtrl.SelectedObject;
            if (selectedObject != null)
            {
                try
                {
                    switch (selectedObject.Type)
                    {
                        case WIObjectType.Server:
                            return project;

                        case WIObjectType.Project:
                            return (selectedObject as WIProjectProvider).GetProject();

                        case WIObjectType.QueriesRoot:
                        case WIObjectType.QueriesGroup:
                        case WIObjectType.Query:
                            {
                                WIProjectProvider provider = (WIProjectProvider)selectedObject.GetType().InvokeMember("ProjectProvider", BindingFlags.GetProperty, null, selectedObject, null);
                                return provider.GetProject();
                            }
                    }
                    throw new NotImplementedException();
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.ToString());
                }
            }
            return project;
        }

        private void GetSelectedColumns()
        {
            WIStoredQuery selectedObject = this.m_tfsTreeCtrl.SelectedObject as WIStoredQuery;
            WorkItemCollection items = selectedObject.ExecQuery();
            if ((items != null) && ((items == null) || (items.Count != 0)))
            {
                if (selectedObject.FolderView == null)
                {
                    selectedObject.FolderView = new OlWIQueryFolderView(items);
                }
                OlWIQueryFolderView folderView = selectedObject.FolderView as OlWIQueryFolderView;
                this.m_Select = string.Empty;
                this.m_Select = this.m_Select + "SELECT ";
                List<OlWIQueryColumn> list = new List<OlWIQueryColumn>();
                this.m_columnsWidthResulGrid.Clear();
                foreach (OlWIQueryColumn column in folderView.Columns)
                {
                    list.Add(column);
                    this.m_columnsWidthResulGrid.Add(column.Width);
                }
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == (list.Count - 1))
                    {
                        this.m_Select = this.m_Select + "[" + this.m_fieldDictionary[list[i].Caption].ReferenceName + "] ";
                    }
                    else
                    {
                        this.m_Select = this.m_Select + "[" + this.m_fieldDictionary[list[i].Caption].ReferenceName + "], ";
                    }
                }
            }
        }

        private Uri GetServer(WIObject item)
        {
            WIObject selectedObject = this.m_tfsTreeCtrl.SelectedObject;
            if (selectedObject != null)
            {
                try
                {
                    switch (selectedObject.Type)
                    {
                        case WIObjectType.Server:
                        case WIObjectType.Project:
                        case WIObjectType.QueriesRoot:
                        case WIObjectType.QueriesGroup:
                        case WIObjectType.Query:
                            {
                                WIProjectProvider provider = (WIProjectProvider)selectedObject.GetType().InvokeMember("ProjectProvider", BindingFlags.GetProperty, null, selectedObject, null);
                                return provider.GetStore().TeamFoundationServer.Uri;
                            }
                    }
                    throw new NotImplementedException();
                }
                catch (Exception exception)
                {
                    LogManager.WriteMessageToCustomLog("Error in GetServer " + exception.ToString());
                }
            }
            return null;
        }

        private void InitAreaPath(WorkItemStore store)
        {
            this.m_comboTreeValue.TreeView.Nodes.Clear();
            foreach (Project project in store.Projects)
            {
                foreach (Node node in project.AreaRootNodes)
                {
                    this.m_comboTreeValue.TreeView.Nodes.Add(this.NodeToTreeNode(node));
                }
            }
        }

        private void InitComboBoxes()
        {
            this.EnableCombobBoxes(false);
            this.m_comboAndOr.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.m_comboField.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.m_comboOperator.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.m_comboValue.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            this.m_comboAndOr.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.And_Or);
            this.m_comboField.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.Field);
            this.m_comboOperator.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.Operator);
            this.m_comboValue.Name = Enum.GetName(typeof(ComboboxName), ComboboxName.Value);
            this.m_comboAndOr.DropDownStyle = ComboBoxStyle.DropDownList;
            this.m_comboField.DropDownStyle = ComboBoxStyle.DropDownList;
            this.m_comboOperator.DropDownStyle = ComboBoxStyle.DropDownList;
            this.m_comboValue.DropDownStyle = ComboBoxStyle.DropDown;
            this.m_comboTreeValue.TreeView.Height = 300;
            this.m_comboTreeValue.BranchSeparator = @"\";
            this.m_comboAndOr.SelectedValueChanged += new EventHandler(this.OnAndOrTextChanged);
            this.m_comboField.SelectedValueChanged += new EventHandler(this.OnFieldTextChanged);
            this.m_comboOperator.SelectedValueChanged += new EventHandler(this.OnOperatorTextChanged);
            this.m_comboOperator.DropDown += new EventHandler(this.OnOperatorDropDown);
            this.m_comboValue.TextChanged += new EventHandler(this.OnValueTextChanged);
            this.m_comboValue.DropDown += new EventHandler(this.OnValueDropDown);
            this.m_comboTreeValue.TreeView.BeforeSelect += new TreeViewCancelEventHandler(this.OnValueBeforeSelect);
            base.Controls.Add(this.m_comboValue);
            base.Controls.Add(this.m_comboOperator);
            base.Controls.Add(this.m_comboField);
            base.Controls.Add(this.m_comboAndOr);
            base.Controls.Add(this.m_comboTreeValue);
            this.m_comboAndOr.Items.AddRange(new string[] { "And", "Or" });
        }

        private void InitInterationPath(WorkItemStore store)
        {
            this.m_comboTreeValue.TreeView.Nodes.Clear();
            foreach (Project project in store.Projects)
            {
                foreach (Node node in project.IterationRootNodes)
                {
                    this.m_comboTreeValue.TreeView.Nodes.Add(this.NodeToTreeNode(node));
                }
            }
        }

        private void InitOperatorsDictionary()
        {
            string[] strArray = new string[] { "=", "<>", "<", ">", "<=", ">=", "In" };
            string[] strArray2 = strArray;
            string[] strArray3 = new string[] { "=", "<>", "<", ">", "<=", ">=", "In", "Contains", "Does Not Contain", "Was Ever" };
            string[] strArray4 = new string[] { "Contains", "Does Not Contain" };
            string[] strArray5 = strArray4;
            string[] strArray6 = new string[] { "Under", "Not Under", "=", "<>", "In" };
            string[] strArray7 = new string[] { "=", "<>", "<", ">", "<=", ">=", "In", "Was Ever" };
            string[] strArray8 = strArray4;
            string[] strArray9 = new string[] { "=", "<>", "In" };
            this.m_operatorsDictionary.Add("Integer", strArray);
            this.m_operatorsDictionary.Add("DateTime", strArray2);
            this.m_operatorsDictionary.Add("String", strArray3);
            this.m_operatorsDictionary.Add("PlainText", strArray4);
            this.m_operatorsDictionary.Add("History", strArray5);
            this.m_operatorsDictionary.Add("TreePath", strArray6);
            this.m_operatorsDictionary.Add("Double", strArray7);
            this.m_operatorsDictionary.Add("Html", strArray8);
            this.m_operatorsDictionary.Add("Team Project", strArray9);
        }

        private void InitTreePath(string path)
        {
            string str = path;
            if (str != null)
            {
                if (!(str == "Iteration Path"))
                {
                    if (str == "Area Path")
                    {
                        this.InitAreaPath(this.m_store);
                    }
                }
                else
                {
                    this.InitInterationPath(this.m_store);
                }
            }
            this.m_comboTreeValue.Visible = false;
            this.m_comboTreeValue.Width = 0;
            this.m_comboTreeValue.Left = this.CellLeft;
            this.m_comboTreeValue.Top = this.CellTop;
            this.m_comboTreeValue.Width = this.CellWidth;
            this.m_comboTreeValue.BringToFront();
            this.m_comboTreeValue.Text = this.m_queryGrid.CurrentCell.Value + "";
            this.m_comboTreeValue.Visible = true;
            this.m_comboTreeValue.Focus();
        }

        private TreeNode NodeToTreeNode(Node node)
        {
            TreeNode node2 = new TreeNode(node.Name);
            foreach (Node node3 in node.ChildNodes)
            {
                node2.Nodes.Add(this.NodeToTreeNode(node3));
            }
            return node2;
        }

        private void OnAndOrTextChanged(object sender, EventArgs e)
        {
            if ((this.m_queryGrid.CurrentCell.ColumnIndex == 1) && !this.m_comboAndOr.Text.Equals(string.Empty))
            {
                this.m_queryGrid.CurrentCell.Value = this.m_comboAndOr.Text;
            }
        }

        private void OnCellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int[] selectedIds = this.m_gridQueryResults.GetSelectedIds();
            new WorkItemForm(this.m_gridQueryResults.WorkItemCollection.Store.GetWorkItem(selectedIds[0]), this.OlProccessor).ShowDialog();
        }

        private void OnCellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if ((e.ColumnIndex == 0) && (e.RowIndex > -1))
            {
                e.Handled = true;
                if (!this.m_queryGrid[e.ColumnIndex, e.RowIndex].Selected)
                {
                    e.Graphics.FillRectangle(new SolidBrush(SystemColors.HighlightText), e.CellBounds);
                    e.Graphics.DrawLine(Pens.Silver, (e.CellBounds.X + e.CellBounds.Width) - 1, e.CellBounds.Y, (e.CellBounds.X + e.CellBounds.Width) - 1, e.CellBounds.Y + e.CellBounds.Height);
                    Rectangle clipBounds = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height - 1);
                    e.PaintContent(clipBounds);
                    if (e.RowIndex == (this.m_queryGrid.Rows.Count - 1))
                    {
                        e.Graphics.DrawLine(Pens.Silver, e.CellBounds.X, (e.CellBounds.Y + e.CellBounds.Height) - 1, e.CellBounds.X + e.CellBounds.Width, (e.CellBounds.Y + e.CellBounds.Height) - 1);
                    }
                }
                else
                {
                    e.Graphics.FillRectangle(this.m_SysBack, e.CellBounds);
                    e.PaintContent(e.CellBounds);
                }
            }
            this.DrawTextLastRow(e);
            if (this.m_allowePaint)
            {
                this.DrawLastRowWithoutSeparateLines(e);
            }
        }

        private void OnCellValueChange(object sender, DataGridViewCellEventArgs e)
        {
        }

        private void OnClick(object sender, EventArgs e)
        {
            this.DisableComboBoxes();
        }

        private void OnColumnsOptions(object sender, EventArgs e)
        {
            WIQLViewForm form = new WIQLViewForm();
            if (this.m_tfsTreeCtrl.SelectedObject != null)
            {
                form.GuidNodeExpand = (this.m_tfsTreeCtrl.SelectedObject.Type != WIObjectType.Server) ? this.m_tfsTreeCtrl.SelectedObject.ID : Guid.Empty;
            }
            form.ShowDialog();
        }

        private void OnContextMenuQueriesMapOpening(object sender, CancelEventArgs e)
        {
            try
            {
                this.m_deleteQueryMenuItem.Enabled = false;
                switch (this.m_tfsTreeCtrl.SelectedObject.Type)
                {
                    case WIObjectType.Server:
                    case WIObjectType.Project:
                    case WIObjectType.QueriesRoot:
                    case WIObjectType.QueriesGroup:
                        return;

                    case WIObjectType.Query:
                        this.m_deleteQueryMenuItem.Enabled = true;
                        this.m_renameQueryContext.Enabled = true;
                        return;
                }
                throw new NotImplementedException();
            }
            catch (Exception exception)
            {
                LogManager.WriteMessageToCustomLog("Error in OnContextMenuQueriesMapOpening " + exception.ToString());
            }
        }

        private void OnCurrentCellChanged(object sender, EventArgs e)
        {
        }

        private void OnDeleteNonFilledClauses(object sender, EventArgs e)
        {
            List<DataGridViewRow> list = new List<DataGridViewRow>();
            foreach (DataGridViewRow row in m_queryGrid.Rows)
            {
                if ((this.m_queryGrid[2, row.Index].Value == null) && (this.m_queryGrid[1, row.Index].Value != null))
                {
                    list.Add(row);
                }
            }
            foreach (DataGridViewRow row in list)
            {
                this.m_queryGrid.Rows.Remove(row);
            }
            if ((list.Count != 0) && (this.m_rowNewValue != 0))
            {
                this.m_rowNewValue = 0;
            }
        }

        private void OnDeleteStoredQuery(object sender, EventArgs e)
        {
            WIStoredQuery selectedObject = this.m_tfsTreeCtrl.SelectedObject as WIStoredQuery;
            if (selectedObject != null)
            {
                this.DeleteStoredQuery(selectedObject);
            }
        }

        private void OnEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            this.DisableComboBoxes();
            if (this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None) == this.m_queryGrid.CurrentCell.RowIndex)
            {
                this.m_queryGrid[1, this.m_queryGrid.CurrentCell.RowIndex].Value = "And";
                this.m_queryGrid[3, this.m_queryGrid.CurrentCell.RowIndex].Value = "=";
                this.AddSimpleRow();
            }
            this.m_queryGrid.SendToBack();
            switch (this.m_queryGrid.CurrentCell.ColumnIndex)
            {
                case 1:
                    if ((this.m_queryGrid.CurrentCell.RowIndex != 0) || (this.m_queryGrid.CurrentCell.ColumnIndex != 1))
                    {
                        this.ComboBoxStart(this.m_comboAndOr);
                        break;
                    }
                    break;

                case 2:
                    this.ComboBoxStart(this.m_comboField);
                    break;

                case 3:
                    this.ComboBoxStart(this.m_comboOperator);
                    break;

                case 4:
                    if (!(((string)this.m_queryGrid[this.m_queryGrid.CurrentCell.ColumnIndex - 2, this.m_queryGrid.CurrentCell.RowIndex].Value) == "Area Path"))
                    {
                        if (((string)this.m_queryGrid[this.m_queryGrid.CurrentCell.ColumnIndex - 2, this.m_queryGrid.CurrentCell.RowIndex].Value) == "Iteration Path")
                        {
                            this.InitTreePath("Iteration Path");
                        }
                        else
                        {
                            this.ComboBoxStart(this.m_comboValue);
                        }
                        break;
                    }
                    this.InitTreePath("Area Path");
                    break;
            }
        }

        private void OnEndUpdate(object sender, EventArgs e)
        {
            List<TreeNode> expandedNodes = this.GetExpandedNodes();
            if (this.m_bEndUpdate)
            {
                TreeNode selectedNode = this.m_tfsTreeCtrl.TreeView.SelectedNode;
                this.m_tfsTreeCtrl.LoadTree();
                this.m_tfsTreeCtrl.TreeView.Update();
                this.m_tfsTreeCtrl.TreeView.SelectedNode = selectedNode;
                this.m_queryGrid.Focus();
                this.m_bEndUpdate = false;
            }
            this.ExpandNodes(expandedNodes);
        }

        private void OnExecute(object sender, EventArgs e)
        {
            WIObject selectedObject = this.m_tfsTreeCtrl.SelectedObject;
            if (selectedObject != null)
            {
                Cursor cursor = this.Cursor;
                try
                {
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        this.BuildQuery();
                        if (this.m_store != null)
                        {
                            StringBuilder builder = new StringBuilder(this.m_queryString);
                            builder.Replace("@project", string.Format("'{0}'", this.GetProject(selectedObject).Name));
                            this.m_gridQueryResults.LoadFromWiql(this.m_store, builder.ToString());
                            this.m_groupBoxResult.Text = string.Format("{0}: {1}", this.GetProject(selectedObject).Name, selectedObject.FolderName);
                            for (int i = 0; i < this.m_columnsWidthResulGrid.Count; i++)
                            {
                                this.m_gridQueryResults.Columns[i].Width = this.m_columnsWidthResulGrid[i];
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                finally
                {
                    this.Cursor = cursor;
                }
            }
        }

        private void OnFieldTextChanged(object sender, EventArgs e)
        {
            if (this.m_queryGrid.CurrentCell.ColumnIndex == 2)
            {
                string text = this.m_comboField.Text;
                if (!this.m_comboField.Text.Equals(string.Empty))
                {
                    this.m_queryGrid.CurrentCell.Value = this.m_comboField.Text;
                    if (this.m_queryGrid.CurrentCell.RowIndex == this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None))
                    {
                        this.AddSimpleRow();
                    }
                }
            }
        }

        private void OnFileSaveQuery(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "wiq files (*.wiq)|*.wiq";
            dialog.FilterIndex = 2;
            dialog.RestoreDirectory = true;
            dialog.FileName = this.m_tfsTreeCtrl.SelectedObject.FolderName;
            WIStoredQuery selectedObject = this.m_tfsTreeCtrl.SelectedObject as WIStoredQuery;
            if (selectedObject != null)
            {
                Project project = this.GetProject(selectedObject);
                this.BuildQuery();
                this.m_queryString = this.m_queryString.Replace("<>", "&lt;&gt;");
                string str = string.Format(Resources.STRING_SAVE_WORKITEM_IN_FILE, this.GetServer(this.m_tfsTreeCtrl.SelectedObject), project.Name, this.m_queryString);
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter writer = new StreamWriter(dialog.FileName))
                    {
                        writer.Write(str);
                    }
                }
            }
        }

        private void OnGroupClausesClick(object sender, EventArgs e)
        {
            int firstSelectedRowIndex = this.FirstSelectedRowIndex;
            int lastSelectedRowIndex = this.LastSelectedRowIndex;
            if (lastSelectedRowIndex < firstSelectedRowIndex)
            {
                CommonGlobal.ReverseVariables(ref firstSelectedRowIndex, ref lastSelectedRowIndex);
            }
            this.m_groupCollection.Add(new Group(firstSelectedRowIndex, lastSelectedRowIndex, this.m_distancePixel));
            this.m_queryGrid.Invalidate();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.EnableControls(false);
            this.InitOperatorsDictionary();
        }

        private void OnOpening(object sender, CancelEventArgs e)
        {
            this.m_ungroupClausesToolStripMenuItem.Enabled = false;
            this.m_groupClausesToolStripMenuItem.Enabled = false;
            if (this.m_queryGrid.SelectedRows.Count >= 2)
            {
                bool bAllowUngroup = false;
                bool bAllowGroup = true;
                int firstSelectedRowIndex = this.FirstSelectedRowIndex;
                int lastSelectedRowIndex = this.LastSelectedRowIndex;
                if (lastSelectedRowIndex < firstSelectedRowIndex)
                {
                    CommonGlobal.ReverseVariables(ref firstSelectedRowIndex, ref lastSelectedRowIndex);
                }
                bAllowGroup = this.CheckToAllowGroup(bAllowGroup, firstSelectedRowIndex, lastSelectedRowIndex);
                this.CheckToAllowUngroup(ref bAllowUngroup, ref bAllowGroup, firstSelectedRowIndex, lastSelectedRowIndex);
                this.m_ungroupClausesToolStripMenuItem.Enabled = bAllowUngroup;
                this.m_groupClausesToolStripMenuItem.Enabled = bAllowGroup;
            }
        }

        private void OnOperatorDropDown(object sender, EventArgs e)
        {
            if (this.m_store != null)
            {
                string str = (string)this.m_queryGrid[this.m_queryGrid.CurrentCell.ColumnIndex - 1, this.m_queryGrid.CurrentCell.RowIndex].Value;
                if (((str != null) && !str.Equals(string.Empty)) && !str.Equals(" "))
                {
                    try
                    {
                        this.m_comboOperator.Items.Clear();
                        FieldDefinition definition = this.m_fieldDictionary[(string)this.m_queryGrid[this.m_queryGrid.CurrentCell.ColumnIndex - 1, this.m_queryGrid.CurrentCell.RowIndex].Value];
                        string[] strArray = null;
                        if (str == "Team Project")
                        {
                            strArray = this.m_operatorsDictionary["Team Project"];
                        }
                        else
                        {
                            strArray = this.m_operatorsDictionary[definition.FieldType.ToString()];
                        }
                        if (strArray != null)
                        {
                            foreach (string str2 in strArray)
                            {
                                this.m_comboOperator.Items.Add(str2);
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        LogManager.WriteMessageToCustomLog("Error in OnOperatorDropDown " + exception.ToString());
                    }
                }
            }
        }

        private void OnOperatorTextChanged(object sender, EventArgs e)
        {
            if ((this.m_queryGrid.CurrentCell.ColumnIndex == 3) && !this.m_comboOperator.Text.Equals(string.Empty))
            {
                this.m_queryGrid.CurrentCell.Value = this.m_comboOperator.Text;
            }
        }

        private void OnPaint(object sender, PaintEventArgs e)
        {
            int num = 0;
            if (this.m_queryGrid.DisplayRectangle.Width < this.m_queryGrid.ClientRectangle.Width)
            {
                num = this.m_queryGrid.ClientRectangle.Width - this.m_queryGrid.DisplayRectangle.Width;
            }
            try
            {
                switch (this.m_queryGrid.CurrentCell.ColumnIndex)
                {
                    case 1:
                        this.m_comboAndOr.Width = this.CellWidth;
                        goto Label_00FC;

                    case 2:
                        this.m_comboField.Width = this.CellWidth;
                        goto Label_00FC;

                    case 3:
                        this.m_comboOperator.Width = this.CellWidth;
                        goto Label_00FC;

                    case 4:
                        this.m_comboValue.Width = this.CellWidth - num;
                        this.m_comboTreeValue.Width = this.CellWidth - num;
                        goto Label_00FC;
                }
            }
            catch
            {
            }
        Label_00FC:
            foreach (Group group in this.m_groupCollection)
            {
                Rectangle rectangle = this.m_queryGrid.GetCellDisplayRectangle(0, group.FirstRow, true);
                Rectangle rectangle2 = this.m_queryGrid.GetCellDisplayRectangle(0, group.LastRow, true);
                using (Pen pen = new Pen(Color.Black))
                {
                    if (rectangle.Left < rectangle2.Left)
                    {
                        Rectangle rectangle3 = this.m_queryGrid.GetCellDisplayRectangle(0, this.m_queryGrid.FirstDisplayedScrollingRowIndex, true);
                        e.Graphics.DrawLine(pen, (rectangle2.Left + (rectangle2.Width / 2)) - group.Distance, rectangle2.Top + (rectangle2.Height / 2), rectangle2.Right, rectangle2.Top + (rectangle2.Height / 2));
                        e.Graphics.DrawLine(pen, (rectangle2.Left + (rectangle2.Width / 2)) - group.Distance, rectangle2.Top + (rectangle2.Height / 2), (rectangle2.Left + (rectangle2.Width / 2)) - group.Distance, rectangle3.Top);
                    }
                    else if (rectangle.Left > rectangle2.Left)
                    {
                        e.Graphics.DrawLine(pen, (rectangle.Left + (rectangle.Width / 2)) - group.Distance, rectangle.Top + (rectangle.Height / 2), rectangle.Right, rectangle.Top + (rectangle.Height / 2));
                        e.Graphics.DrawLine(pen, (rectangle.Left + (rectangle.Width / 2)) - group.Distance, rectangle.Top + (rectangle.Height / 2), (rectangle.Left + (rectangle.Width / 2)) - group.Distance, this.m_queryGrid.Bottom);
                    }
                    else
                    {
                        e.Graphics.DrawLine(pen, (rectangle.Left + (rectangle.Width / 2)) - group.Distance, rectangle.Top + (rectangle.Height / 2), rectangle.Right, rectangle.Top + (rectangle.Height / 2));
                        e.Graphics.DrawLine(pen, (rectangle2.Left + (rectangle2.Width / 2)) - group.Distance, rectangle2.Top + (rectangle2.Height / 2), rectangle2.Right, rectangle2.Top + (rectangle2.Height / 2));
                        e.Graphics.DrawLine(pen, (int)((rectangle.Left + (rectangle.Width / 2)) - group.Distance), (int)(rectangle.Top + (rectangle.Height / 2)), (int)((rectangle2.Left + (rectangle2.Width / 2)) - group.Distance), (int)(rectangle2.Top + (rectangle2.Height / 2)));
                    }
                }
            }
            if (this.m_allowePaint && this.m_queryGrid.Rows[this.m_queryGrid.Rows.GetLastRow(DataGridViewElementStates.None)].Displayed)
            {
                e.Graphics.DrawString(Resources.CLICK_HERE_TO_ADD_A_CLAUSE, new Font("Arial", 8f), Brushes.Black, (PointF)this.m_pointLastCell);
            }
        }

        private void OnQueryGridSizeChange(object sender, EventArgs e)
        {
            this.m_queryGrid.Columns[4].Width = this.m_queryGrid.Width - (((this.m_queryGrid.Columns[1].Width + this.m_queryGrid.Columns[2].Width) + this.m_queryGrid.Columns[0].Width) + this.m_queryGrid.Columns[3].Width);
        }

        private void OnRemoveClauses(object sender, EventArgs e)
        {
            this.RemoveRows();
        }

        private void OnRenameQuery(object sender, EventArgs e)
        {
            WIStoredQuery selectedObject = this.m_tfsTreeCtrl.SelectedObject as WIStoredQuery;
            if (selectedObject != null)
            {
                this.RenameStoredQuery(selectedObject);
            }
        }

        private void OnSavePrivateQueries(object sender, EventArgs e)
        {
            this.SaveQuery(QueryScope.Private);
        }

        private void OnSavePublicQueries(object sender, EventArgs e)
        {
            this.SaveQuery(QueryScope.Public);
        }

        private void OnScroll(object sender, ScrollEventArgs e)
        {
            this.DisableComboBoxes();
            this.m_queryGrid.Invalidate();
            this.m_rowNewValue = e.NewValue;
        }

        private void OnTFSSelectesChange(object sender, EventArgs e)
        {
            WIObject selectedObject = this.m_tfsTreeCtrl.SelectedObject;
            this.DisableComboBoxes();
            switch (selectedObject.Type)
            {
                case WIObjectType.Server:
                case WIObjectType.Project:
                case WIObjectType.QueriesRoot:
                case WIObjectType.QueriesGroup:
                    this.m_queryGrid.Rows.Clear();
                    this.m_allowePaint = false;
                    this.m_toolStripTextBoxQueryName.Text = string.Empty;
                    this.EnableControls(false);
                    break;

                case WIObjectType.Query:
                    {
                        this.m_queryGrid.Enabled = true;
                        this.m_queryGrid.Rows.Clear();
                        this.m_toolStripTextBoxQueryName.Text = selectedObject.FolderName;
                        this.EnableCombobBoxes(false);
                        this.m_toolStripTextBoxQueryName.Text = selectedObject.FolderName;
                        this.EnableControls(true);
                        this.m_groupCollection.Clear();
                        this.m_distancePixel = 0;
                        Cursor cursor = this.Cursor;
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;
                            StoredQuery query = null;
                            try
                            {
                                query = (selectedObject as WIStoredQuery).GetQuery();
                                this.m_store = (selectedObject as WIStoredQuery).GetStore();
                            }
                            catch
                            {
                                MessageBox.Show(Resources.STRING_QUERY_CANNOT_BE_RECEIVED_FROM_SERVER, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            }
                            if (this.m_store != null)
                            {
                                this.FillFieldComboBox(this.m_store);
                                this.InitAreaPath(this.m_store);
                            }
                            try
                            {
                                this.QuerySelected(query);
                            }
                            catch (Exception exception)
                            {
                                LogManager.WriteMessageToCustomLog("Error in parsing stored query " + exception.ToString());
                                Debug.WriteLine("Error in parsing stored query " + exception.ToString());
                            }
                        }
                        finally
                        {
                            this.Cursor = cursor;
                        }
                        break;
                    }
                default:
                    throw new NotImplementedException();
            }
        }

        private void OnUnGroupClauses(object sender, EventArgs e)
        {
            int firstSelectedRowIndex = this.FirstSelectedRowIndex;
            int lastSelectedRowIndex = this.LastSelectedRowIndex;
            if (lastSelectedRowIndex < firstSelectedRowIndex)
            {
                CommonGlobal.ReverseVariables(ref firstSelectedRowIndex, ref lastSelectedRowIndex);
            }
            Group item = null;
            foreach (Group group2 in this.m_groupCollection)
            {
                if ((group2.FirstRow == firstSelectedRowIndex) && (group2.LastRow == lastSelectedRowIndex))
                {
                    item = group2;
                }
                if (group2.Distance != 0)
                {
                    this.m_distancePixel = 0;
                }
            }
            this.m_groupCollection.Remove(item);
            this.m_queryGrid.Invalidate();
        }

        private void OnUpdateQuery(object sender, EventArgs e)
        {
            WIStoredQuery selectedObject = this.m_tfsTreeCtrl.SelectedObject as WIStoredQuery;
            if (selectedObject != null)
            {
                Cursor cursor = this.Cursor;
                try
                {
                    try
                    {
                        this.Cursor = Cursors.WaitCursor;
                        StoredQuery query = selectedObject.GetQuery();
                        this.BuildQuery();
                        query.QueryText = this.m_queryString;
                        query.Name = this.m_toolStripTextBoxQueryName.Text;
                        query.Update();
                        this.Update(selectedObject);
                        MessageBox.Show(Resources.STRING_QUERY_HAS_BEEN_UPDATED_SUCCESFULLY, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    catch (Exception exception)
                    {
                        MessageBox.Show(exception.Message, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                }
                finally
                {
                    this.Cursor = cursor;
                }
            }
        }

        private void OnValueBeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (this.m_queryGrid.CurrentCell.ColumnIndex == 4)
            {
                this.m_comboTreeValue.Visible = false;
                this.m_queryGrid.CurrentCell.Value = this.m_comboTreeValue.Text;
            }
        }

        private void OnValueDropDown(object sender, EventArgs e)
        {
            if (this.m_store != null)
            {
                this.m_comboValue.Items.Clear();
                string str = (string)this.m_queryGrid[this.m_queryGrid.CurrentCell.ColumnIndex - 2, this.m_queryGrid.CurrentCell.RowIndex].Value;
                if ((str != null) && (!str.Equals(string.Empty) || !str.Equals(" ")))
                {
                    Cursor cursor = this.Cursor;
                    try
                    {
                        try
                        {
                            this.Cursor = Cursors.WaitCursor;
                            FieldDefinition definition = this.m_fieldDictionary[this.m_queryGrid[this.m_queryGrid.CurrentCell.ColumnIndex - 2, this.m_queryGrid.CurrentCell.RowIndex].Value as string];
                            AllowedValuesCollection allowedValues = definition.AllowedValues;
                            foreach (string str2 in allowedValues)
                            {
                                this.m_comboValue.Items.Add(str2);
                            }
                            if (definition.ReferenceName.Equals("System.TeamProject"))
                            {
                                this.m_comboValue.Items.AddRange(new string[] { "@project" });
                            }
                            if (definition.ReferenceName.Equals("System.AssignedTo"))
                            {
                                this.m_comboValue.Items.AddRange(new string[] { "@me" });
                            }
                            if (definition.FieldType.ToString() == "DateTime")
                            {
                                this.m_comboValue.Items.AddRange(new string[] { "@Today", "@Today - 1", "@Today - 7", "@Today - 30" });
                            }
                        }
                        catch (Exception exception)
                        {
                            LogManager.WriteMessageToCustomLog("Error in OnValueDropDown " + exception.ToString());
                        }
                    }
                    finally
                    {
                        this.Cursor = cursor;
                    }
                }
            }
        }

        private void OnValueTextChanged(object sender, EventArgs e)
        {
            if (this.m_queryGrid.CurrentCell.ColumnIndex == 4)
            {
                this.m_queryGrid.CurrentCell.Value = this.m_comboValue.Text;
            }
        }

        private void QuerySelected(StoredQuery query)
        {
            QueryParseManager manager = new QueryParseManager(query.QueryText, this.m_store);
            this.m_groupCollection = manager.GroupCollection;
            foreach (QueryParameters parameters in manager.QueryList)
            {
                DataGridViewRow row = new DataGridViewRow();
                object[] values = new object[6];
                values[0] = "";
                values[1] = parameters.AndOr;
                values[2] = parameters.Field;
                values[3] = parameters.Operator;
                values[4] = parameters.Value;
                this.m_queryGrid.Rows.Add(values);
            }
            this.AddSimpleRow();
            this.m_queryGrid[1, 0].ReadOnly = true;
            this.m_queryGrid.Invalidate();
        }

        private void RaiseDeleteNonFilledClauses()
        {
            if (this.m_queryGrid.Rows.Count > 0)
            {
                this.DeleteNonFilledClauses(this, EventArgs.Empty);
            }
        }

        private void RemoveRows()
        {
            this.DisableComboBoxes();
            if (this.m_groupCollection.Count > 0)
            {
                if (MessageBox.Show(Resources.STRING_EXISTING_CLAUSE_GROUPING_WILL_ALSO_BE_DELETED, this.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
                {
                    this.RemoveSelectedRows();
                    this.m_groupCollection.Clear();
                    this.m_distancePixel = 0;
                }
            }
            else
            {
                this.RemoveSelectedRows();
            }
            this.m_rowNewValue = 0;
        }

        private void RemoveSelectedRows()
        {
            foreach (DataGridViewRow row in this.m_queryGrid.SelectedRows)
            {
                this.m_queryGrid.Rows.Remove(row);
            }
            this.m_queryGrid[1, 0].Value = string.Empty;
        }

        private void RenameStoredQuery(WIStoredQuery item)
        {
            try
            {
                StoredQuery query = item.GetQuery();
                string queryName = this.m_toolStripTextBoxQueryName.Text.Trim(new char[] { ' ' });
                if (queryName.Equals((string)null) || queryName.Equals(string.Empty))
                {
                    MessageBox.Show(this, Resources.STRING_ENTER_VALID_QUERY_NAME, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                else
                {
                    Project project = this.GetProject(item);
                    if (project == null)
                    {
                        MessageBox.Show(string.Format(Resources.STRING_PROJECT_NOT_FOUND, project.Name), this.Name, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    else
                    {
                        try
                        {
                            QueryScope queryScope = item.QueryScope;
                            string queryText = query.QueryText;
                            string description = query.Description;
                            this.DeleteStoredQuery(item);
                            project.StoredQueries.Add(new StoredQuery(queryScope, queryName, queryText, description));
                        }
                        catch (UnauthorizedAccessException exception)
                        {
                            MessageBox.Show(exception.Message, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        }
                        catch (Exception exception3)
                        {
                            Exception exception2 = exception3;
                            MessageBox.Show(exception2.Message, this.Name, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        }
                        this.Update(item);
                    }
                }
            }
            catch (Exception exception4)
            {
                LogManager.WriteMessageToCustomLog("Error in RenameQuery " + exception4.ToString());
            }
        }

        private void SaveQuery(QueryScope queryScope)
        {
            WIStoredQuery selectedObject = this.m_tfsTreeCtrl.SelectedObject as WIStoredQuery;
            if (selectedObject != null)
            {
                Project project = this.GetProject(selectedObject);
                if (project == null)
                {
                    MessageBox.Show(string.Format(Resources.STRING_PROJECT_NOT_FOUND, project.Name), Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                else
                {
                    this.BuildQuery();
                    try
                    {
                        QueryScope scope = queryScope;
                        project.StoredQueries.Add(new StoredQuery(scope, this.m_toolStripTextBoxQueryName.Text, this.m_queryString, string.Empty));
                        MessageBox.Show(Resources.QUERY_ADD_SUCCESSFULL, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    catch (UnauthorizedAccessException exception)
                    {
                        MessageBox.Show(exception.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    }
                    catch (Exception exception2)
                    {
                        MessageBox.Show(exception2.Message, Resources.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        LogManager.WriteMessageToCustomLog("Error in SaveOldQuery " + exception2.ToString());
                    }
                    this.Update(selectedObject);
                }
            }
        }

        private int SortByName(string s1, string s2)
        {
            return s1.CompareTo(s2);
        }

        private void Update(WIStoredQuery wiObject)
        {
            this.m_bEndUpdate = true;
            wiObject.ProjectProvider.EndUpdate += new EventHandler(this.OnEndUpdate);
            wiObject.ProjectProvider.Update();
        }

        // Properties
        private int CellLeft
        {
            get
            {
                int num = this.m_queryGrid.Location.X + this.m_gbQueryBody.Location.X;
                if (this.m_queryGrid.CurrentCell.ColumnIndex != 0)
                {
                    for (int i = 0; i < this.m_queryGrid.CurrentCell.ColumnIndex; i++)
                    {
                        num += this.m_queryGrid.Columns[i].Width;
                    }
                }
                return (num += this.m_queryGrid.RowHeadersWidth);
            }
        }

        private int CellTop
        {
            get
            {
                int num = this.m_queryGrid.Location.Y + this.m_gbQueryBody.Location.Y;
                if (this.m_queryGrid.CurrentCell.RowIndex != 0)
                {
                    for (int i = 0; i < this.m_queryGrid.CurrentCell.RowIndex; i++)
                    {
                        num += this.m_queryGrid.Rows[i].Height;
                    }
                }
                return (num += this.m_queryGrid.ColumnHeadersHeight);
            }
        }

        private int CellWidth
        {
            get
            {
                return this.m_queryGrid.Columns[this.m_queryGrid.CurrentCell.ColumnIndex].Width;
            }
        }

        private int FirstSelectedRowIndex
        {
            get
            {
                return this.m_queryGrid.SelectedRows[this.m_queryGrid.SelectedRows.Count - 1].Index;
            }
        }

        private int LastSelectedRowIndex
        {
            get
            {
                return this.m_queryGrid.SelectedRows[0].Index;
            }
        }

        private new string Name
        {
            get
            {
                return Resources.UI_QUERY_MANAGER_CAPTION;
            }
        }

        private IOlWorkItemProcessor OlProccessor
        {
            get
            {
                return this.m_olProccessor;
            }
            set
            {
                if (object.ReferenceEquals(value, null))
                {
                    throw new NullReferenceException();
                }
                this.m_olProccessor = value;
            }
        }
    }
}
